package cn.fastoo.service;

import cn.fastoo.common.dao.BatchDao;
import cn.fastoo.common.dao.SmsrecordDao;
import cn.fastoo.common.dao.UserBaseDao;
import cn.fastoo.common.entity.Batch;
import cn.fastoo.common.entity.Smsrecord;
import cn.fastoo.common.entity.UserBase;
import cn.fastoo.common.sampleframe.search.Search;
import cn.fastoo.common.utils.BigDecimalUtil;
import cn.fastoo.common.utils.Constant;
import cn.fastoo.common.utils.DateUtils;
import cn.fastoo.common.utils.JedisDao;
import cn.fastoo.task.MtMessage;
import cn.fastoo.task.SaveMtMessageQueue;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import redis.clients.jedis.Jedis;

import java.util.Date;


@Component
@Transactional
public class SmsrecordService {

    private static Logger logger = LoggerFactory.getLogger(SmsrecordService.class);

    @Autowired
    private UserBaseDao userBaseDao;
    @Autowired
    private SmsrecordDao smsrecordDao;
    @Autowired
    private BatchDao batchDao;
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private UserService userService;



    public void save(Long userBaseId, Smsrecord smsrecord) {
        //保存记录
        smsrecordDao.insert(smsrecord);
        //扣费
        UserBase userBase = userBaseDao.findById(userBaseId);
        Double balance = BigDecimalUtil.sub(userBase.getBalance(),smsrecord.getPrice()*smsrecord.getFeeCount());
        userBase.setBalance(balance);
        userBaseDao.update(userBase);
    }


    public synchronized void saveBatchToRedis(UserBase userBase,String apiKey,String signName,String batchName,  String das,String msg, String timing,Integer dasize,Integer totalFeeNum) {
        logger.info("["+apiKey+"]开始提交批次");
        //获取同步锁,保存批次
//        Jedis jedis = null;
        try {
//            jedis = JedisDao.getJedis();
//            jedis.select(Constant.DB);

//            if (jedis.setnx("running","1")==1) { //返回1是不存在 0是存在
                Batch batch = new Batch();
                batch.setUserBaseId(userBase.getId());
                batch.setApiKey(apiKey);
                batch.setBatchName(batchName);
                batch.setStatus(1);
                if (StringUtils.isNotBlank(timing)) {
                    Date timingDate = DateUtils.convertStringToDate(timing, Constant.FORMAT_YMD_HM);
                    batch.setTiming(timingDate);
                }
                batch.setSubmitTimeDt(Integer.valueOf(DateUtils.formatDate(new Date(),"yyyyMMdd")));
                batch.setContent(msg);
                batch.setTotalNum(dasize);
                batch.setTotalFeeNum(totalFeeNum);
                batchDao.insert(batch);

                MtMessage mtMessage = new MtMessage();
                mtMessage.setUserBaseId(userBase.getId());
                mtMessage.setBatchId(batch.getId());
                mtMessage.setLoginName(userBase.getLoginName());
                mtMessage.setDas(das);
                mtMessage.setMsg(msg);
                mtMessage.setTiming(timing);
                mtMessage.setSignName(signName);
                mtMessage.setApiKey(apiKey);
                SaveMtMessageQueue.put(jdbcTemplate,smsrecordDao,userService,mtMessage);
//                jedis.del("running");

                logger.info("end running");
//            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
//            if (jedis!=null) {
//                jedis.close();
//            }
        }


    }


    public Integer sended(Long batchId) {
        return Integer.valueOf(smsrecordDao.count(new Search().addSearchFilter("EQ_batchId",batchId).addSearchFilter("NEQ_mtStatus",0)).toString());
    }
}
